package handlers

import (
	"github.com/gin-gonic/gin"
	"perm-guard/models"
	"strconv"
)

func RoleAdd(c *gin.Context) {
	name := c.PostForm("name")
	face := c.PostForm("face")
	sex := c.PostForm("sex")
	userID, _ := strconv.Atoi(c.PostForm("user_id"))

	data := models.Role{

		Name:   name,
		Face:   face,
		Sex:    sex,
		UserID: userID,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配角色失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "分配角色成功",
	})
	return
}

func PowerAdd(c *gin.Context) {
	content := c.PostForm("content")
	roleID, _ := strconv.Atoi(c.PostForm("role_id"))
	data := models.Power{

		Content: content,
		RoleID:  roleID,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配权限失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "分配权限成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.User{}).Count(&count)

	var user []models.User
	err := models.DB.Order("id desc").Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": gin.H{
			"count": count,
			"data":  user,
		},
	})
	return
}
